package org.lhq.controller;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.lhq.entity.Directory;
import org.lhq.entity.UserFile;
import org.lhq.service.DirectoryService;
import org.lhq.service.FileService;
import org.lhq.service.UserFileService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("review")
@Slf4j
public class PreviewController {
	@Resource
	FileService fileService;
	@Resource
	UserFileService userFileService;
	@Resource
	DirectoryService directoryService;
	@GetMapping("{fileId}")
	public void review(@PathVariable Long fileId, HttpServletResponse response) throws IOException, URISyntaxException, InterruptedException {

		UserFile downloadFile = this.userFileService.getUserFileDao().selectById(fileId);
		String fileName;
		Directory dir = null;
		if(downloadFile == null){
			dir = this.directoryService.getDirById(fileId);
		}
		if (dir!=null){
			List<Directory> directories = new ArrayList<>(1);
			directories.add(dir);
			OutputStream outputStream = response.getOutputStream();
			ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(dir.getDirectoryName(), "UTF-8"));
			this.fileService.multipleDownload(directories, null, zipOutputStream, dir.getDirectoryName());
			zipOutputStream.close();
		}
		if (downloadFile!= null && StrUtil.isNotEmpty(downloadFile.getFileType())) {
			fileName = downloadFile.getFileName() + "." + downloadFile.getFileType();
		} else {
			fileName = downloadFile.getFileName();
		}
		try {
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
			this.fileService.download(downloadFile.getFilePath(), response.getOutputStream());
		} catch (Exception e) {
			log.error("发生了不可描述的错误:", e);
		}
	}
}
